import { NavBar, InfiniteScroll } from 'antd-mobile';
import { useHistory, useParams } from 'react-router-dom';
import classNames from 'classnames';
import styles from './Article.module.scss';
import DOMpurify from 'dompurify';
import ContentLoader from 'react-content-loader';
// import { throttle } from 'lodash';

import { CommentItem } from './CommentItem/CommentItem';
import { CommentFooter } from './CommentFooter/CommentFooter';
import { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { followAuthor, getArticleById } from '@/store/actions/article';
import { RootState } from '@/types/store';

import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // 只要导入这个样式即可

export const Article = () => {
  // hooks
  const history = useHistory();
  const dispatch = useDispatch();

  // 页面状态
  const params = useParams<{ id: string }>();
  // 文章详情
  const detail = useSelector((state: RootState) => state.article.detail);
  // 页面加载状态
  const [isLoading, setIsLoading] = useState(true);
  // 文章详情ref
  const wrapperRef = useRef<HTMLDivElement>(null);
  // 作者ref
  const authorRef = useRef<HTMLDivElement>(null);
  // 评论列表Ref
  const commentRef = useRef<HTMLDivElement>(null);
  // 作者信息是否显示在标题栏的状态
  const [isShowAuthor, setIsShowAuthor] = useState(false);

  // wrapper 滚动事件监听
  useEffect(() => {
    // 获取原生 DOM 的异常处理
    const wrapper = wrapperRef.current;
    if (!wrapper) return;
    const author = authorRef.current;
    if (!author) return;

    // wrapper 滑动要计算author距离顶部的距离
    // const wrapperOnScroll = () => {
    //   const top = author.getBoundingClientRect().top;
    //   console.log('wrapper 滚动, 作者距离顶部的距离', top);
    //   if (top < 11) {
    //     // 标题栏显示作者
    //     setIsShowAuthor(true);
    //   } else {
    //     // 不显示
    //     setIsShowAuthor(false);
    //   }
    // };
    // 截流版本，使用第三方库
    const wrapperOnScroll = throttle(() => {
      const top = author.getBoundingClientRect().top;
      console.log('wrapper 滚动, 作者距离顶部的距离', top);
      if (top < 11) {
        // 标题栏显示作者
        setIsShowAuthor(true);
      } else {
        // 不显示
        setIsShowAuthor(false);
      }
    }, 100);

    wrapper.addEventListener('scroll', wrapperOnScroll);

    // 别忘记返回清理函数
    return () => {
      wrapper.removeEventListener('scroll', wrapperOnScroll);
    };
  });

  function throttle(cb: () => void, delay: number) {
    let valid = true; // 给截流函数生成闭包用
    return function () {
      // 第一次执行，肯定通过。
      if (!valid) {
        //休息时间 暂不接客
        return false;
      }
      // 一旦开始执行，后边的就不再接待
      valid = false;
      setTimeout(() => {
        cb();
        // 此次执行完毕，准备下次执行
        valid = true;
      }, delay);
    };
  }

  // 根据文章id获取文章详情
  useEffect(() => {
    console.log('文章id', params.id);
    const fetchData = async () => {
      // 发起请求
      await dispatch(getArticleById(params.id));
      setIsLoading(false);
    };
    fetchData();
  }, [params.id, dispatch]);

  // 底部评论点击事件处理函数
  const onShowComment = () => {
    console.log('评论被点击了');
    const wrapper = wrapperRef.current;
    if (!wrapper) return;
    const comment = commentRef.current;
    if (!comment) return;

    const commentTop = comment.getBoundingClientRect().top;
    wrapper.scrollTo({ top: commentTop - 45 });
  };

  // 关注取消关注
  const handleFollow = () => {
    console.log('关注或取消关注');
    dispatch(followAuthor(detail.aut_id, detail.is_followed));
  };

  // 事件
  const loadMoreComments = async () => {
    console.log('加载更多评论');
  };

  // 文章详情渲染
  const renderArticle = () => {
    if (isLoading) {
      // 根据当前页面结构，设计好的 loading 效果
      return (
        <ContentLoader
          speed={2}
          width={375}
          height={230}
          viewBox="0 0 375 230"
          backgroundColor="#f3f3f3"
          foregroundColor="#ecebeb"
        >
          <rect x="16" y="8" rx="3" ry="3" width="340" height="10" />
          <rect x="16" y="26" rx="0" ry="0" width="70" height="6" />
          <rect x="96" y="26" rx="0" ry="0" width="50" height="6" />
          <rect x="156" y="26" rx="0" ry="0" width="50" height="6" />
          <circle cx="33" cy="69" r="17" />
          <rect x="60" y="65" rx="0" ry="0" width="45" height="6" />
          <rect x="304" y="65" rx="0" ry="0" width="52" height="6" />
          <rect x="16" y="114" rx="0" ry="0" width="340" height="15" />
          <rect x="263" y="208" rx="0" ry="0" width="94" height="19" />
          <rect x="16" y="141" rx="0" ry="0" width="340" height="15" />
          <rect x="16" y="166" rx="0" ry="0" width="340" height="15" />
        </ContentLoader>
      );
    } else {
      // 文章详情
      return (
        <div className="wrapper" ref={wrapperRef}>
          <div className="article-wrapper">
            <div className="header">
              <h1 className="title">{detail.title}</h1>

              <div className="info">
                <span>{detail.pubdate}</span>
                <span>{detail.read_count} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              <div className="author" ref={authorRef}>
                <img
                  src={
                    detail.aut_photo ||
                    'http://geek.itheima.net/images/user_head.jpg'
                  }
                />
                <span className="name">{detail.aut_name}</span>
                <span
                  className={classNames('follow', {
                    followed: detail.is_followed,
                  })}
                  onClick={handleFollow}
                >
                  {detail.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            </div>

            <div className="content">
              <div
                className="content-html dg-html"
                dangerouslySetInnerHTML={{
                  __html: DOMpurify.sanitize(detail.content),
                }}
              />
              <div className="date">发布文章时间：{detail.pubdate}</div>
            </div>
          </div>

          <div className="comment" ref={commentRef}>
            <div className="comment-header">
              <span>全部评论（{detail.comm_count}）</span>
              <span>{detail.like_count} 点赞</span>
            </div>

            <div className="comment-list">
              <CommentItem />
              <CommentItem />
              <CommentItem />
              <CommentItem />
              <CommentItem />
              <CommentItem />

              <InfiniteScroll hasMore={false} loadMore={loadMoreComments} />
            </div>
          </div>
        </div>
      );
    }
  };

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <svg className="icon">
                <use xlinkHref={'#icongengduo'}></use>
              </svg>
            </span>
          }
        >
          {isShowAuthor && (
            <div className="nav-author">
              <img
                src={
                  detail.aut_photo ||
                  'http://geek.itheima.net/images/user_head.jpg'
                }
              />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classNames('follow', {
                  followed: detail.is_followed,
                })}
                onClick={handleFollow}
              >
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter onShowComment={onShowComment} />
      </div>
    </div>
  );
};
